package com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.service.ShopsService;


import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 接受与发送部门信息
 * @author ailinfei
 *
 */
public class ShopsServlet extends HttpServlet {
	private static final String CONTENT_TYPE = "text/plain; charset=UTF-8";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		this.StringToJson(req, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	/**                                                          
	 * 输出信息
	 * @param response
	 * @param content
	 * @throws IOException                                                                                          
	 */
	private void print(HttpServletResponse response, String content)
			throws IOException {
		response.setContentType(CONTENT_TYPE);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		PrintWriter write = response.getWriter();
		write.print(content);
		write.close();
	}

	/**                                                          
	 * 获取商户信息json
	 * @param req
	 * @param response
	 * @throws ServletException
	 * @throws IOException                                                                                          
	 */
	private void StringToJson(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		JSONObject resultJSON = new JSONObject(); 
		req.setCharacterEncoding("UTF-8");
		String key=req.getParameter("key");
	    double lng=Double.parseDouble(req.getParameter("lng"));
	    double lat=Double.parseDouble(req.getParameter("lat"));
	    int pageNum=Integer.parseInt(req.getParameter("page_num"));
	    System.out.println("pageNum:"+pageNum);
		ShopsService service = new ShopsService();
		try {
			 resultJSON.accumulate("shops", service.getShops(key, 31.250159, 121.448568,pageNum));    
			 System.out.println(resultJSON.toString(1,1));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		  this.print(response, resultJSON.toString(1,1));

	}

}
